//
//  AddressInstituteNearbyViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/10/10.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//
#import "AddressInstituteNearbyViewController.h"
#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Location/BMKLocationService.h>
#import <BaiduMapAPI_Search/BMKPoiSearch.h>
#import <BaiduMapAPI_Map/BMKAnnotation.h>
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>
#import <BaiduMapAPI_Map/BMKPinAnnotationView.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import "SearchResultViewController.h"
@interface AddressInstituteNearbyViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKPoiSearchDelegate,UISearchBarDelegate,BMKSuggestionSearchDelegate,UIViewControllerTransitioningDelegate>

@property (nonatomic,strong) BMKMapView *mapView;//地图视图
@property(nonatomic,strong)BMKLocationService *service;
@property(nonatomic,strong)BMKPoiSearch *poiSearch;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property(nonatomic,strong)UISearchBar *searchBar;
@property(nonatomic,strong)BMKSuggestionSearch *searcher;
@end

@implementation AddressInstituteNearbyViewController

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
        
    }
    return _dataArray;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createBMKMapView];
    [self createBackBtn];
    // Do any additional setup after loading the view.
}

/**
 创建返回按钮
 */
-(void)createBackBtn{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.backgroundColor = [UIColor clearColor];
    UIImageView *backImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigator_btn_back"]];
    backImg.frame = CGRectMake(10, 10, 22, 22);
    [backBtn addSubview:backImg];
    [backBtn addTarget:self action:@selector(dismissMap:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(50);
        make.left.equalTo(self.view.mas_left).offset(10);
        make.size.mas_equalTo(CGSizeMake(67, 23));
    }];
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor whiteColor];
    [self searchBarInitInView:backView];
    [self.view addSubview:backView];
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backBtn.mas_right).offset(10);
        make.height.mas_equalTo(60);
        make.top.equalTo(self.view.mas_top).offset(50);
        make.right.equalTo(self.view.mas_right).offset(-10);
    }];
}
- (UISearchBar *)searchBarInitInView:(UIView *)view
{
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 14, WIDTH - 100 , 32)];
        UIImage* searchBarBg = [self GetImageWithColor:[UIColor clearColor] andHeight:32.0f];
        [_searchBar setBackgroundImage:searchBarBg];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"请输入机构关键字";
        _searchBar.showsCancelButton = NO;
        [view addSubview:_searchBar];
        
    }
    return _searchBar;
}
#pragma mark 实现搜索条背景透明化

- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height{
    
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    
    UIGraphicsBeginImageContext(r.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return img;
    
}
-(void)dismissMap:(UIButton *)btn{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)createBMKMapView{
    sleep(0.7);
    self.mapView = [[BMKMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.delegate = self;
    [self.mapView setMapType:BMKMapTypeStandard];
    self.mapView.trafficEnabled = YES;
    self.mapView.showMapPoi = YES;
    self.mapView.rotateEnabled = NO;
    self.mapView.scrollEnabled = YES;
    self.mapView.showMapScaleBar = YES;
    self.mapView.zoomLevel = 3;
    [self.view addSubview:self.mapView];
    self.service = [[BMKLocationService alloc] init];
    self.service.delegate = self;
    [self.service startUserLocationService];
}
#pragma makr -地图定位的代理方法
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    self.mapView.showsUserLocation = YES;
    [self.mapView updateLocationData:userLocation];
    self.mapView.centerCoordinate = userLocation.location.coordinate;
    self.mapView.zoomLevel = 18;
    //初始化搜索
    self.poiSearch =[[BMKPoiSearch alloc] init];
    self.poiSearch.delegate = self;
    
    BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc] init];
    option.pageIndex = 0;
    option.pageCapacity = 50;
    option.radius = 5000;
    option.location = userLocation.location.coordinate;
    option.keyword = @"儿童机构";
    //    根据中心点，半径和检索词发起周边搜索
    BOOL flag = [self.poiSearch poiSearchNearBy:option];
    if (flag) {
        NSLog(@"搜索成功");
        [self.service stopUserLocationService];
        
    }else{
        NSLog(@"搜索失败");
    }
}
#pragma mark -搜索的代理方法
-(void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult *)poiResult errorCode:(BMKSearchErrorCode)errorCode{
    //若搜索成功
    if (errorCode ==BMK_SEARCH_NO_ERROR) {
        //POI信息类 //poi列表
        for (BMKPoiInfo *info in poiResult.poiInfoList) { [self.dataArray addObject:info];
            //初始化一个点的注释 //只有三个属性
            BMKPointAnnotation *annotoation = [[BMKPointAnnotation alloc] init];
            //坐标
            annotoation.coordinate = info.pt;
            //title
            annotoation.title = info.name;
            NSLog(@"这是你想要的名字%@",annotoation.title);
            //子标题
            annotoation.subtitle = info.address;
            //将标注添加到地图上
            [self.mapView addAnnotation:annotoation];
        } }
    
}
-(void)onGetPoiDetailResult:(BMKPoiSearch *)searcher result:(BMKPoiDetailResult *)poiDetailResult errorCode:(BMKSearchErrorCode)errorCode{
    NSLog(@"%@",poiDetailResult.name);
}

#pragma mark -地图的代理方法

-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        //        根据注视点创建标注
        BMKPinAnnotationView *newAnnotion = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotion.pinColor = BMKPinAnnotationColorRed;
        newAnnotion.animatesDrop = YES;
        NSLog(@"走了么");
        return newAnnotion;
    }
    return nil;
}
-(void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views{
    for (NSInteger i = 0; i < views.count; i++) {
        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *) [views objectAtIndex:i];
        [mapView selectAnnotation:annotationView.annotation animated:YES];
    }
    
}

/**
 当选中一个annotionview时调用此接口
 
 */
-(void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view{
    BMKPoiDetailSearchOption *option = [[BMKPoiDetailSearchOption alloc] init];
    BMKPoiInfo *infor = self.dataArray.firstObject;
    option.poiUid = infor.uid;
    
    BOOL flag= [self.poiSearch poiDetailSearch:option];
    if (flag) {
        NSLog(@"检索成功");
    }else{
        NSLog(@"检索失败");
    }
}
#pragma mark -searchBar的代理方法
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    SearchResultViewController *resultVc = [[SearchResultViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:resultVc];
    nav.transitioningDelegate = self;
    nav.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:nav animated:YES
                     completion:^{
                         [self.searchBar resignFirstResponder];
     }];
    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
    return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
//    SearchResultViewController *resultVc = [[SearchResultViewController alloc] init];
//    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:resultVc];
//    nav.transitioningDelegate = self;
//    nav.modalPresentationStyle = UIModalPresentationCustom;
//    [self presentViewController:nav animated:YES
//                     completion:^{
//                         [self.searchBar resignFirstResponder];
//                     }];
//    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
   return YES;
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    BMKSuggestionSearchOption *option = [[BMKSuggestionSearchOption alloc] init];
    NSString *cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentLocaltion"];
    option.cityname = cityName;
    option.keyword = searchText;
    self.searcher = [[BMKSuggestionSearch alloc] init];
    self.searcher.delegate = self;
    BOOL flag = [self.searcher suggestionSearch:option];
    if(flag)
    {
        NSLog(@"建议搜索发送成功");
    }
    else
    {
        NSLog(@"建议搜索发送失败");
    }
}

/**
 搜索藐视

 */
-(void)onGetSuggestionResult:(BMKSuggestionSearch *)searcher result:(BMKSuggestionResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        NSLog(@"%@---%@-----%@=====%@", result.keyList, result.cityList, result.districtList, result.ptList);
        for (NSString *str1 in result.keyList) {
            NSLog(@"%@",str1);
        }
        for (NSString *str1 in result.cityList) {
            NSLog(@"%@",str1);
        }
        for (NSString *str1 in result.districtList) {
            NSLog(@"%@",str1);
        }
        for (NSString *str1 in result.ptList) {
            NSLog(@"%@",str1);
        }
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil;
    self.service.delegate = nil;
    self.searcher.delegate = nil;
    self.poiSearch.delegate = nil;
    [self.searchBar resignFirstResponder];
}
-(void)dealloc{
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil;
    self.service.delegate = nil;
    self.searcher.delegate = nil;
    self.poiSearch.delegate = nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
